<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-depotName>
                <el-input
                  v-model="formInfo.data.depotName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择出库仓库"
                >
                  <template #append>
                    <el-icon @click="selectExportDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  v-model:query="scanInfo.query"
                  :api="scanInfo.api"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <el-form-item
                        v-if="
                          scope.row.codeType === 1 || scope.row.codeType === 4
                        "
                        class="margin-bottom"
                      >
                        <div class="page-table-input-number-wrapper">
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.largeUnitQty`"
                                :rules="[
                                  {
                                    validator: $validate.positiveAndZero,
                                    trigger: 'blur',
                                  },
                                ]"
                              >
                                <el-input-number
                                  v-model.lazy="scope.row.largeUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  :min="0"
                                  :max="largeMax(scope.row)"
                                  @change="
                                    changeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.largeUnitQty`
                                    )
                                  "
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.unitName }}
                              </div>
                            </div>
                            <div
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                              class="page-table-input-number-item"
                            >
                              <el-form-item>
                                <el-input-number
                                  v-model.lazy="scope.row.smallUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="smallMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.calcUnitName }}
                              </div>
                            </div>
                          </div>
                          <div
                            v-if="scope.row.qtyOperateMode === 2"
                            class="page-table-input-number-right"
                          >
                            {{ $fn.qtyFormatter(scope.row.qty) }}
                          </div>
                        </div>
                      </el-form-item>
                      <span
                        v-else-if="
                          scope.row.codeType === 2 || scope.row.codeType === 3
                        "
                        >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                      >
                    </template>
                    <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      v-model:query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />

    <SelectDepotStorage
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      v-model:query="selectDepotStorageInfo.query"
      :right-query-params="selectDepotStorageInfo.rightQueryParams"
      :left-query-params="selectDepotStorageInfo.leftQueryParams"
      :left-table-key="selectDepotStorageInfo.leftTableKey"
      :right-table-key="selectDepotStorageInfo.rightTableKey"
      :api="selectDepotStorageInfo.api"
      :exclude-query-list="selectDepotStorageInfo.excludeQueryList"
      :show-price="$permission('accountExportOrder:price')"
      stockIdStr="accountDepotStockId"
      @callback="selectDepotStorageCallBack"
    />
    <selectIndividual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:left-query-obj="individualInfo.leftQuery"
      v-model:right-query-obj="individualInfo.rightQuery"
      v-model:info-list="individualInfo.productInfo"
      :request-right-list="!!exportId"
      v-model:right-api="individualInfo.rightApi"
      v-model:left-api="individualInfo.leftApi"
      v-model:right-vo="individualInfo.rightVo"
      :show-price="$permission('accountExportOrder:price')"
      :scan-info="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="accountExportOrderModify">
import selectIndividual from '../components/individual'
import ScanInputBox from '../components/ScanInputBox'
import { getCoreSystemConfigAll } from '@/api/core'
import {
  batchValidateAccountExportOrder,
  createAccountExportOrder,
  updateAccountExportOrder,
  getAccountExportOrderById,
  accountExportOrderDetailCustomizeListAll,
  getBeginningDepotStockPage,
  beginningDepotStockCustomizeScan,
} from '@/api/beginning'
import { beginningDepotStockValidate } from '@/api/stock'
import { getCustomizeSetting } from '@/api/customize'
import moment from 'moment'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'exportId'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref(null)
const scanInfo = ref({
  api: beginningDepotStockCustomizeScan,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: '',
      // validateExpire: false
    },
  },
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
  },
  fieldList: [
    {
      label: '出库单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '出库仓库',
      value: 'depotName',
      type: 'slot',
      require: true,
    },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.exportId &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择出库仓库', trigger: 'change' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    isCargoSpaceManage: 0,
  },
})
const selectDepotStorageInfo = ref({
  //库存产品
  leftTableKey:
    'beginningAccountExportOrderSelectProductLeft-com.slip.spd.entity.vo.beginning.BeginningDepotStockVO',
  rightTableKey:
    'beginningAccountExportOrderSelectProductRight-com.slip.spd.entity.vo.beginning.BeginningDepotStockVO',
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  api: getBeginningDepotStockPage,
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  rightQueryParams: {
    stockAvailableCalcQtyGt: 0,
    extantStockAvailableCalcQtyGt: 0,
  },
  leftQueryParams: {
    stockAvailableCalcQtyGt: 0,
    extantStockAvailableCalcQtyGt: 0,
  },
})
const individualInfo = ref({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  rightApi: accountExportOrderDetailCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getBeginningDepotStockPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})

const canAddProduct = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.deptId
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length && !tableInfo.value.isSysGroup) {
      console.log(tableInfo.value.data)
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  { deep: true }
)
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.value.isSysGroup
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]
  let key = []
  tableInfo.value.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.value.map.has(newKey)) {
    if (
      oldInfo.groupConcatAccountDepotStockIds.includes(
        detail.accountDepotStockId.toString()
      )
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.value.map.get(newKey)
        if (
          await value.groupConcatAccountDepotStockIds.includes(
            detail.accountDepotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}

async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据
  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      data,
      tableInfo.value.sysGroup,
      tableInfo.value.map,
      accountExportOrderDetailCustomizeListAll,
      props.exportId,
      individualInfo.value.rightVo,
      'stockAvailableCalcQty',
      'accountDepotStockId',
      'groupConcatAccountDepotStockIds'
    )
    tableInfo.value.map = map
    tableInfo.value.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
async function onCallBackScanData(data, callback) {
  //扫码回调
  let { mergeDetail, detail } = data
  if (tableInfo.value.data && tableInfo.value.data.length) {
    let items = tableInfo.value.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatAccountDepotStockIds)
        let bool = arr.includes(detail.accountDepotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.stockAvailableCalcQty, row.calcQty)
          if (num <= 1) {
            console.log()

            return row.calcQty === row.stockAvailableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.value.sysGroup,
    tableInfo.value.map,
    accountExportOrderDetailCustomizeListAll,
    props.exportId,
    individualInfo.value.rightVo,
    'stockAvailableCalcQty',
    'accountDepotStockId',
    'groupConcatAccountDepotStockIds'
  )
  tableInfo.value.map = map
  tableInfo.value.data = [...map.values()]
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.value.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.value.selectObj) {
    individualInfo.value.selectObj[key].value = data[key]
  }
  if (props.exportId) {
    individualInfo.value.leftQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.value.data.isConsignBusiness,
    }
    individualInfo.value.rightQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.value.data.isConsignBusiness,
    }
  }
  individualInfo.value.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatAccountDepotStockIds,
  }
  individualInfo.value.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.value.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.value.data.depotId,
  }
  individualInfo.value.leftQuery = {
    ...individualInfo.value.leftQuery,
    ...individualInfo.value.selectObj,
  }
  individualInfo.value.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.value.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.exportId,
  }
  individualInfo.value.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  console.log(data)
  if (data.details && data.details.length) {
    tableInfo.value.map.set(data.key, data)
    let index = tableInfo.value.data.findIndex((item) => item.key === data.key)
    console.log(index)
    if (index !== -1) {
      tableInfo.value.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
function getMain() {
  getAccountExportOrderById(props.exportId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      selectDepotStorageInfo.value.query.isConsignBusiness.value =
        resp.data.isConsignBusiness
      scanInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      scanInfo.value.query.queryParams.depotId = resp.data.depotId
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.exportId
  getList()
}
function getList() {
  //修改请求明细信息
  accountExportOrderDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success && resp.data.length) {
        let data = resp.data
        data.forEach((item) => {
          //将返回的数据变成Map形式
          let key = []
          tableInfo.value.sysGroup.forEach((row) => {
            let obj = {}
            obj.columnName = row.columnName
            obj.asTbName = row.asTbName
            obj.value = item[row.key]
            key.push(obj)
          })

          item.key = JSON.stringify(key)
          if (!tableInfo.value.isSysGroup) {
            item.groupConcatAccountDepotStockIds =
              item.accountDepotStockId.toString()
            item.groupSize = 1
            let row = proxy.$fn.deepClone(item)
            delete row.key
            item.details = [row]
          }
          tableInfo.value.map.set(item.key, item)
        })
        tableInfo.value.data = data
      }
    }
  )
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getParams(details) {
  let _newDetails = details.filter((item) => item.calcQty > 0)
  return _newDetails.map((item) => {
    return {
      calcQty: item.calcQty || '',
      depotStockId: item.accountDepotStockId || '',
      isConsignBusiness: formInfo.value.data.isConsignBusiness,
    }
  })
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = tableInfo.value.data.filter(
      (row) => row.productId && row.qty
    )
    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let details = proxy.$fn.filterBlacklist(newDetails)
    //校验过期产品是否准许出库
    getCoreSystemConfigAll().then((resp) => {
      if (resp && resp.success) {
        let find = resp.data.find(
          (item) => item.systemConfigCode === 'allow_expire_out'
        )
        if (find) {
          let expire = validateExpire(newDetails)
          if (find.value === '1') {
            if (expire) {
              proxy
                .$confirm(expire + ',是否继续?', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  dangerouslyUseHTMLString: true,
                })
                .then(() => {
                  const data = formInfo.value.data
                  data.mergeDetails = details
                  const validateApi = batchValidateAccountExportOrder
                  validateApi(data).then((resp) => {
                    if (resp && resp.success) {
                      let params = getParams(details)
                      beginningDepotStockValidate(params).then((res) => {
                        if (
                          res &&
                          res.code &&
                          res.code == 200 &&
                          (res.msgType === 'messageBox' || res.success)
                        ) {
                          const api = data.id
                            ? updateAccountExportOrder
                            : createAccountExportOrder
                          api(data).then((resp) => {
                            if (resp && resp.success) {
                              showDialog.value = false
                              proxy.$emit('returnModify', false)
                            }
                          })
                        }
                      })
                    }
                  })
                  /* const validateApi = batchValidateAccountExportOrder
                  validateApi(data).then((resp) => {
                    if (resp && resp.success) {
                      const api = data.id
                        ? updateAccountExportOrder
                        : createAccountExportOrder
                      api(data).then((resp) => {
                        if (resp && resp.success) {
                          showDialog.value = false
                          proxy.$emit('returnModify', false)
                        }
                      })
                    }
                  }) */
                  return
                })
                .catch(() => {
                  return
                })
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details
              const validateApi = batchValidateAccountExportOrder
              validateApi(data).then((resp) => {
                if (resp && resp.success) {
                  let params = getParams(details)
                  beginningDepotStockValidate(params).then((res) => {
                    console.log(res)
                    if (
                      res &&
                      res.code &&
                      res.code == 200 &&
                      (res.msgType === 'messageBox' || res.success)
                    ) {
                      const api = data.id
                        ? updateAccountExportOrder
                        : createAccountExportOrder
                      api(data).then((resp) => {
                        if (resp && resp.success) {
                          showDialog.value = false
                          proxy.$emit('returnModify', false)
                        }
                      })
                    }
                  })
                }
              })

              /* const validateApi = batchValidateAccountExportOrder
              validateApi(data).then((resp) => {
                if (resp && resp.success) {
                  const api = data.id
                    ? updateAccountExportOrder
                    : createAccountExportOrder
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      showDialog.value = false
                      proxy.$emit('returnModify', false)
                    }
                  })
                }
              }) */
            }
          } else {
            if (expire) {
              proxy.$alert(expire + '，不允许出库！', '操作提示', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
              })
              return
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details

              const validateApi = batchValidateAccountExportOrder
              validateApi(data).then((resp) => {
                if (resp && resp.success) {
                  let params = getParams(details)
                  beginningDepotStockValidate(params).then((res) => {
                    if (
                      res &&
                      res.code &&
                      res.code == 200 &&
                      (res.msgType === 'messageBox' || res.success)
                    ) {
                      const api = data.id
                        ? updateAccountExportOrder
                        : createAccountExportOrder
                      api(data).then((resp) => {
                        if (resp && resp.success) {
                          showDialog.value = false
                          proxy.$emit('returnModify', false)
                        }
                      })
                    }
                  })
                }
              })

              /* const validateApi = batchValidateAccountExportOrder
              validateApi(data).then((resp) => {
                if (resp && resp.success) {
                  const api = data.id
                    ? updateAccountExportOrder
                    : createAccountExportOrder
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      showDialog.value = false
                      proxy.$emit('returnModify', false)
                    }
                  })
                }
              }) */
            }
          }
        } else {
          const data = formInfo.value.data
          data.mergeDetails = details
          const validateApi = batchValidateAccountExportOrder
          validateApi(data).then((resp) => {
            if (resp && resp.success) {
              let params = getParams(details)
              beginningDepotStockValidate(params).then((res) => {
                if (
                  res &&
                  res.code &&
                  res.code == 200 &&
                  (res.msgType === 'messageBox' || res.success)
                ) {
                  const api = data.id
                    ? updateAccountExportOrder
                    : createAccountExportOrder
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      showDialog.value = false
                      proxy.$emit('returnModify', false)
                    }
                  })
                }
              })
            }
          })

          /* const validateApi = batchValidateAccountExportOrder
          validateApi(data).then((resp) => {
            if (resp && resp.success) {
              const api = data.id
                ? updateAccountExportOrder
                : createAccountExportOrder
              api(data).then((resp) => {
                if (resp && resp.success) {
                  showDialog.value = false
                  proxy.$emit('returnModify', false)
                }
              })
            }
          }) */
        }
      }
    })
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
//选择出库仓库
function selectExportDepot() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    formInfo.value.data.depotName = data.name
    formInfo.value.data.deptName = data.deptName || ''
    formInfo.value.data.deptId = data.deptId || ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    scanInfo.value.query.queryParams.depotId = data.id
    selectDepotStorageInfo.value.excludeQueryList = []
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    scanInfo.value.query.queryParams.depotId = ''
    selectDepotStorageInfo.value.excludeQueryList = []
  }
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.value.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.value.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.value.query.depotId.value = formInfo.value.data.depotId
  selectDepotStorageInfo.value.visible = true
}
async function selectDepotStorageCallBack(rows) {
  //库存产品返回
  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.value.sysGroup,
    tableInfo.value.map,
    accountExportOrderDetailCustomizeListAll, //个体弹窗右边数据接口
    props.exportId,
    individualInfo.value.rightVo, //个体弹窗右边表格配置
    'stockAvailableCalcQty',
    'accountDepotStockId',
    'groupConcatAccountDepotStockIds'
  )
  tableInfo.value.map = map
  tableInfo.value.data = [...map.values()]
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => item.key !== row.key
    )
    let key = row.key
    tableInfo.value.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selections.forEach((row) => {
          for (let [key, value] of tableInfo.value.map) {
            if (key === row.key) {
              tableInfo.value.map.delete(key)
            }
          }
        })
        tableInfo.value.data = tableInfo.value.data.filter((row) => {
          return !tableInfo.value.selections.includes(row)
        })
      })
  }
}
function getOtherList(params, api) {
  api(params).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let rows = resp.data
        .filter((item) => item.stockQty > 0)
        .map((row) => {
          return {
            ...row,
            id: null,
            qty: 0,
          }
        })
        .sort((a, b) => {
          return b.productId - a.productId
        })
      tableInfo.value.data = rows
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'beginningAccountExportOrderModify-com.slip.spd.entity.vo.account.AccountExportOrderDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.value.isSysGroup = true
        }
      }
      filterInfo.value.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置
  let param = {
    tableKey:
      'beginningAccountExportOrderSelectProductLeft-com.slip.spd.entity.vo.beginning.BeginningDepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.value.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'accountDepotStockId',
        })
        obj['accountDepotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      scanInfo.value.query.customizeUserVO = data
      individualInfo.value.selectObj = obj
      tableInfo.value.sysGroup = arr
      if (props.exportId) {
        getMain()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'beginningAccountExportOrderModifySingleRight-com.slip.spd.entity.vo.account.AccountExportOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.value.rightVo = res.data
    }
  })
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.exportId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('accountExportOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('accountExportOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('accountExportOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getInvdividualRightCustomize()
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
